const db = require('../config/db');
const { sendError } = require('../utils/response');

module.exports = {
  // 添加收藏
  async addFavorite(userId, productId) {
    // 检查商品是否存在
    const [products] = await db.execute(
      'SELECT id FROM products WHERE id = ? AND status = "active"',
      [productId]
    );
    
    if (products.length === 0) {
      throw new Error('商品不存在或已下架');
    }
    
    // 检查是否已收藏
    const [existing] = await db.execute(
      'SELECT id FROM favorites WHERE user_id = ? AND product_id = ?',
      [userId, productId]
    );
    
    if (existing.length > 0) {
      throw new Error('商品已在收藏夹中');
    }
    
    const [result] = await db.execute(
      'INSERT INTO favorites (user_id, product_id) VALUES (?, ?)',
      [userId, productId]
    );
    
    return result.affectedRows > 0;
  },

  // 移除收藏
  async removeFavorite(userId, productId) {
    const [result] = await db.execute(
      'DELETE FROM favorites WHERE user_id = ? AND product_id = ?',
      [userId, productId]
    );
    
    if (result.affectedRows === 0) {
      throw new Error('收藏不存在');
    }
    
    return true;
  },

  // 获取用户收藏列表
  async getUserFavorites(userId, page = 1, limit = 10) {
    const offset = (page - 1) * limit;
    
    const [favorites] = await db.execute(
      'SELECT f.*, p.name, p.price, p.images FROM favorites f ' +
      'JOIN products p ON f.product_id = p.id ' +
      'WHERE f.user_id = ? AND p.status = "active" ORDER BY f.created_at DESC LIMIT ? OFFSET ?',
      [userId, limit, offset]
    );
    
    // 获取总数用于分页
    const [total] = await db.execute(
      'SELECT COUNT(*) as count FROM favorites f ' +
      'JOIN products p ON f.product_id = p.id ' +
      'WHERE f.user_id = ? AND p.status = "active"',
      [userId]
    );
    
    return {
      favorites,
      pagination: {
        total: total[0].count,
        page,
        limit,
        totalPages: Math.ceil(total[0].count / limit)
      }
    };
  },

  // 检查是否已收藏
  async checkFavorite(userId, productId) {
    const [favorites] = await db.execute(
      'SELECT id FROM favorites WHERE user_id = ? AND product_id = ?',
      [userId, productId]
    );
    
    return favorites.length > 0;
  }
};